import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  IconButton,
  Tooltip,
  Paper,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button
} from '@mui/material';
import { Edit as EditIcon } from '@mui/icons-material';
import { useNovel } from '../../context/NovelContext';
import { TreeItem } from '../../utils/file/fileSystem';

interface EditorProps {
  currentItem: TreeItem | null;
}

const Editor: React.FC<EditorProps> = ({ currentItem }) => {
  const { updateItem } = useNovel();
  const [content, setContent] = useState<string>('');

  // 对话框状态
  const [titleDialogOpen, setTitleDialogOpen] = useState(false);
  const [editedTitle, setEditedTitle] = useState('');

  useEffect(() => {
    if (currentItem) {
      setContent(currentItem.content || '');
      setEditedTitle(currentItem.name);
    } else {
      setContent('');
      setEditedTitle('');
    }
  }, [currentItem]);

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value);
    if (currentItem) {
      updateItem(currentItem.id, { content: e.target.value });
    }
  };

  // 打开标题编辑对话框
  const handleOpenTitleDialog = () => {
    if (currentItem) {
      setEditedTitle(currentItem.name);
      setTitleDialogOpen(true);
    }
  };

  // 关闭标题编辑对话框
  const handleCloseTitleDialog = () => {
    setTitleDialogOpen(false);
  };

  // 保存编辑的标题
  const handleSaveTitle = () => {
    if (currentItem && editedTitle.trim()) {
      updateItem(currentItem.id, { name: editedTitle.trim() });
    }
    setTitleDialogOpen(false);
  };

  return (
    <Box sx={{
      height: '100%',
      display: 'flex',
      flexDirection: 'column',
      padding: 2,
      bgcolor: '#ffffff'
    }}>
      {/* 标题区域 */}
      {currentItem ? (
        <Paper
          elevation={0}
          sx={{
            mb: 2,
            p: 1,
            display: 'flex',
            alignItems: 'center',
            borderBottom: '1px solid #e0e0e0'
          }}
        >
          <Typography
            variant="h5"
            component="h1"
            sx={{
              flexGrow: 1,
              fontWeight: 'bold',
              color: '#333'
            }}
          >
            {currentItem.name}
          </Typography>
          <Tooltip title="编辑标题">
            <IconButton
              size="small"
              onClick={handleOpenTitleDialog}
              sx={{ ml: 1 }}
            >
              <EditIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Paper>
      ) : (
        <Paper
          elevation={0}
          sx={{
            mb: 2,
            p: 2,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            bgcolor: '#f5f5f5',
            color: '#757575'
          }}
        >
          <Typography variant="subtitle1">
            请从左侧选择章节进行编辑
          </Typography>
        </Paper>
      )}

      {/* 内容编辑区域 */}
      <Box sx={{ flexGrow: 1, position: 'relative' }}>
        {currentItem ? (
          <TextField
            multiline
            fullWidth
            variant="outlined"
            placeholder="开始写作..."
            value={content}
            onChange={handleContentChange}
            sx={{
              height: '100%',
              '& .MuiOutlinedInput-root': {
                height: '100%',
                padding: 2,
                display: 'flex',
                alignItems: 'flex-start'
              },
              '& .MuiOutlinedInput-input': {
                height: '100%',
                overflow: 'auto',
                lineHeight: 1.8,
                fontSize: '1rem',
                fontFamily: '"Noto Serif SC", serif',
                textIndent: '2em'
              }
            }}
          />
        ) : (
          <Box
            sx={{
              height: '100%',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              bgcolor: '#f5f5f5',
              color: '#757575',
              borderRadius: 1
            }}
          >
            <Typography variant="body1">
              未选择章节
            </Typography>
          </Box>
        )}
      </Box>

      {/* 标题编辑对话框 */}
      <Dialog
        open={titleDialogOpen}
        onClose={handleCloseTitleDialog}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>编辑章节标题</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="标题"
            type="text"
            fullWidth
            value={editedTitle}
            onChange={(e) => setEditedTitle(e.target.value)}
            variant="outlined"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && editedTitle.trim()) {
                e.preventDefault();
                handleSaveTitle();
              }
            }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseTitleDialog} color="inherit">
            取消
          </Button>
          <Button
            onClick={handleSaveTitle}
            color="primary"
            disabled={!editedTitle.trim()}
          >
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Editor; 